package com.qf.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @author wgy
 * @version V1.0
 * @project gp12_xiaomi
 * @package com.qf.controller
 * @description: ${TODO}
 * @date 2022/6/22 11:19
 */
public class BaseServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        //开闭原则：扩展开放，修改关闭
        String methodName = request.getParameter("method");
        try {
            Method method=this.getClass().getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
            if(method!=null){
                String url= (String) method.invoke(this,request,response);
                if(url!=null&&url.trim().length()!=0){
                    //判断转发或重定向
                    if(url.startsWith("redirect:")){
                        //重定向
                        url=url.substring(url.indexOf(":")+1);
                        response.sendRedirect(request.getContextPath()+url);
                    }else{
                        //转发
                        request.getRequestDispatcher(url).forward(request, response);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("方法不存在...");
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
